package com.mock.ems.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.mock.base.util.CollectionUtil;
import com.mock.base.util.StringUtil;
import com.mock.ems.common.JsonResult;
import com.mock.ems.utils.TGlCateUtil;

import java.util.*;

public class ShopSortController extends Controller {

    public void index(){ renderJsp("/page/shopsort/list.jsp");}

    public void pagination(){

        int limit = getParaToInt("limit");
        int offset = getParaToInt("offset");
        int pageNumber = (offset / limit) + 1;

        String selectSql = "select *";
        StringBuilder exceptSelectSQL = new StringBuilder(" from t_gl_cate where type_key_ = 'ShopCate'");

        List<Object> params = new ArrayList<Object>();

        exceptSelectSQL.append(" order by id_ desc");

        Page<Record> page = Db.paginate(pageNumber,limit,selectSql,exceptSelectSQL.toString(),params.toArray());

        if(CollectionUtil.isNotEmpty(page.getList())){
            page.getList().stream().forEach(item->{
                    item.set("is_show_",item.getStr("is_show_").equals("online_store") ? "线上商家" :
                            item.getStr("is_show_").equals("oto") ? "线下商家" : "未知类型");
            });
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", page.getTotalRow());
        returnMap.put("rows", page.getList());
        renderJson(returnMap);

    }

    public void edit(){

        String id = getPara("id");
        Record shopSort = Db.findById("t_gl_cate","id_",id);
        if(shopSort != null){
            setAttr("shopSort",shopSort);
        }

        renderJsp("/page/shopsort/add.jsp");
    }

    @Before(Tx.class)
    public void save(){

        String id = getPara("id");
        Record shopSort = new Record();
        if(StringUtil.isNotEmpty(id)){
            shopSort = Db.findById("t_gl_cate","id_",id);
        }
        shopSort.set("name_",getPara("name")).set("is_show_",getPara("isShow"));
        if(StringUtil.isNotEmpty(id)){
            Db.update("t_gl_cate","id_",shopSort);
        }else{
            shopSort.set("type_key_","ShopCate");
            Long id_ = TGlCateUtil.genLid();
            shopSort.set("id_",id_);
            Db.save("t_gl_cate","id_",shopSort);
        }

        renderJson(new JsonResult().status("000").show("保存成功"));
    }


}
